package com.wyr.admin.controller;

import com.alibaba.fastjson2.JSONObject;
import com.wyr.admin.mq.DynamicQueueService;
import com.wyr.common.annotation.RateLimit;
import com.wyr.common.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * mq管理
 *
 * @author wangyiren
 * @version 1.0
 * &#064;title MqController
 * &#064;description
 * &#064;date 2025/03/06 14:37
 */
@Slf4j
@Tag(name = "mq管理")
@RestController
@RequestMapping("mq")
public class MqController {

    /**
     * tts topic
     */
    @Value("${zp.tts_topic}")
    private String zpTtsTopic;

    /**
     * 调用记录 topic
     */
    @Value("${zp.invoke_topic}")
    private String invokeTopic;

    /**
     * 翻译队列 topic
     */
    @Value("${zp.translate_topic}")
    private String translateTopic;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private DynamicQueueService dynamicQueueService;

    /**
     * 用户登录
     *
     * @param traceId
     * @param data
     * &#064;description
     * @return: com.wyr.common.vo.Result<?>
     * @author wangyiren
     * &#064;date 2025/3/21 09:55
     */
    @RateLimit(qps = 2, timeout = 1)
    @Operation(summary = "动态mq")
    @Parameters({
            @Parameter(name = "traceId", description = "traceId", required = true, in = ParameterIn.QUERY),
            @Parameter(name = "data", description = "data", required = true, in = ParameterIn.QUERY),
    })
    @GetMapping("test")
    public Result<?> test(String traceId, String data) {
        //使用会话id，动态创建和绑定tts专属队列
        dynamicQueueService.bindDynamicQueueToListener(getDynamicQueueName(traceId));
        // 异步执行tts语音合成
        Map<String, Object> params = new HashMap<>(2);
        params.put("traceId", traceId);
        params.put("data", data);
        amqpTemplate.convertAndSend(getDynamicQueueName(traceId), JSONObject.toJSONString(params));

        // 正常队列
        amqpTemplate.convertAndSend(invokeTopic, JSONObject.toJSONString(params));
        amqpTemplate.convertAndSend(translateTopic, JSONObject.toJSONString(params));
        return Result.ok();
    }


    private String getDynamicQueueName(String sid) {
        return String.format("%s_%s", zpTtsTopic, sid);
    }

}
